<template>
  <el-dialog
    custom-class="random-parts-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="设置随机配件"
    :visible.sync="isPartsDialog"
    width="70%"
    :before-close="handleClose"
  >
    <div class="random-parts-content">
      <div class="parts-table-container">
        <el-form :model="formData" ref="ruleForm">
          <el-table
            :header-cell-style="{ 'background-color': '#f8f9fa' }"
            :data="formData.partsTableData"
            style="width: 100%"
            empty-text="暂无配件信息"
          >
            <el-table-column label="配件名称" min-width="150">
              <template slot-scope="scope">
                <el-form-item :prop="`partsTableData[${scope.$index}].name`" :rules="rules.name">
                  <el-input clearable v-model="scope.row.name" placeholder="请输入配件名称"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="型号" min-width="120">
              <template slot-scope="scope">
                <el-form-item :prop="`partsTableData[${scope.$index}].model`" :rules="rules.model">
                  <el-input clearable v-model="scope.row.model" placeholder="请输入型号"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="启用日期" min-width="140">
              <template slot-scope="scope">
                <el-form-item
                  :prop="`partsTableData[${scope.$index}].enableDate`"
                  :rules="rules.enableDate"
                >
                  <el-date-picker
                    v-model="scope.row.enableDate"
                    type="date"
                    placeholder="选择启用日期"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="数量" min-width="100">
              <template slot-scope="scope">
                <el-form-item
                  :prop="`partsTableData[${scope.$index}].quantity`"
                  :rules="rules.quantity"
                >
                  <el-input
                    v-model.number="scope.row.quantity"
                    controls-position="right"
                    style="width: 100%"
                  ></el-input>
                  <!-- <el-input-number
                    v-model="scope.row.quantity"
                    :min="1"
                    :max="999"
                    controls-position="right"
                    style="width: 100%"
                  ></el-input-number>-->
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="备注" min-width="150">
              <template slot-scope="scope">
                <el-form-item :prop="`partsTableData[${scope.$index}].remarks`">
                  <el-input clearable v-model="scope.row.remarks" placeholder="请输入备注"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button
                  @click="handleDelete(scope.$index)"
                  type="text"
                  size="small"
                  style="color: #f56c6c;"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>

      <div class="dialog-footer">
        <div class="footer-actions">
          <el-button class="add-parts-btn" size="mini" @click="handleAdd" icon="el-icon-plus">添加配件</el-button>
        </div>
        <div class="footer-buttons">
          <el-button size="mini" @click="handleClose">取消</el-button>
          <el-button size="mini" @click="handleSubmit" type="primary">确认</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "RandomPartsDialog",
  props: {
    // 是否显示对话框
    visible: {
      type: Boolean,
      default: false
    },
    // 初始配件数据
    initialData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isPartsDialog: false,
      formData: {
        partsTableData: []
      },
      rules: {
        name: [
          {
            required: true,
            message: "配件名称不能为空",
            trigger: ["blur", "change"]
          }
        ],
        model: [
          {
            required: true,
            message: "型号不能为空",
            trigger: ["blur", "change"]
          }
        ],
        enableDate: [
          {
            required: true,
            message: "启用日期不能为空",
            trigger: ["blur", "change"]
          }
        ],
        quantity: [
          {
            required: true,
            message: "数量不能为空",
            trigger: ["blur", "change"]
          },
          {
            type: "number",
            min: 1,
            message: "数量必须大于0",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  watch: {
    visible: {
      immediate: true,
      handler(newVal) {
        this.isPartsDialog = newVal;
      }
    },
    isPartsDialog(newVal) {
      if (newVal) {
        this.initData();
      }
      this.$emit("update:visible", newVal);
    },
    initialData: {
      immediate: true,
      handler(newVal) {
        this.formData.partsTableData = this.formatPartsData(newVal);
      }
    }
  },
  methods: {
    // 初始化数据
    initData() {
      if (this.formData.partsTableData.length === 0) {
        this.formData.partsTableData = [this.createEmptyPart()];
      }
    },

    // 格式化配件数据
    formatPartsData(data) {
      if (!data || data.length === 0) {
        return [this.createEmptyPart()];
      }
      return data.map(item => ({
        name: item.name || "",
        model: item.model || "",
        enableDate: item.enableDate || "",
        quantity: item.quantity || 1,
        remarks: item.remarks || ""
      }));
    },

    // 创建空配件项
    createEmptyPart() {
      return {
        name: "",
        model: "",
        enableDate: "",
        quantity: 1,
        remarks: ""
      };
    },

    // 关闭对话框
    handleClose() {
      this.isPartsDialog = false;
      this.$emit("close");
    },

    // 提交表单
    handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 过滤空行
          const validData = this.formData.partsTableData.filter(
            item => item.name && item.model && item.enableDate
          );

          this.$emit("submit", validData);
          this.handleClose();
        } else {
          this.$message.error("请填写完整的配件信息");
          return false;
        }
      });
    },

    // 添加配件
    handleAdd() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.formData.partsTableData.push(this.createEmptyPart());
          // 滚动到底部
          this.$nextTick(() => {
            const container = this.$el.querySelector(".parts-table-container");
            if (container) {
              container.scrollTop = container.scrollHeight;
            }
          });
        } else {
          this.$message.warning("请先完成当前配件的填写");
        }
      });
    },

    // 删除配件
    handleDelete(index) {
      if (this.formData.partsTableData.length <= 1) {
        this.$message.warning("至少保留一个配件");
        return;
      }
      this.formData.partsTableData.splice(index, 1);
      // this.$confirm("确定要删除这个配件吗？", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // })
      //   .then(() => {
      //     this.formData.partsTableData.splice(index, 1);
      //   })
      //   .catch(() => {});
    }
  }
};
</script>

<style scoped lang="scss">
.random-parts-content {
  display: flex;
  flex-direction: column;
  height: 60vh;
}

.parts-table-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 5px;
  margin-bottom: 15px;

  ::v-deep .el-table {
    .el-form-item {
      margin-bottom: 0;
    }

    .el-form-item__error {
      position: absolute;
      top: 100%;
      left: 0;
      line-height: 1;
      padding-top: 2px;
    }
  }
}

.dialog-footer {
  border-top: 1px solid #eaeaea;
  // padding-top: 15px;
  background: #fff;
  padding: 0 10px 10px 0;
  box-sizing: border-box;
  .footer-actions {
    padding: 10px;
    box-sizing: border-box;

    .add-parts-btn {
      border: 1px dashed #409eff;
      color: #409eff;
      background: #f0f7ff;

      &:hover {
        background: #ecf5ff;
        border-color: #409eff;
      }
    }
  }

  .footer-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

// 对话框样式
::v-deep .random-parts-dialog {
  .el-dialog__header {
    background: linear-gradient(135deg, #409eff, #1a4b8c);

    .el-dialog__title {
      color: white;
      font-weight: 600;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: white;
      }
    }
  }

  .el-dialog__body {
    padding: 20px;
  }
}
</style>